//
//  HomeViewController.m
//  EasyToTesco2.0
//
//  Created by 杨森 on 16/5/30.
//  Copyright © 2016年 EasyToTesco. All rights reserved.
//

#import "HomeViewController.h"
#import "XRCarouselView.h"
#import "CenterMenuView.h"

#import "CLHomeHeader.h"

#import "FirstHomeCell.h"
#import "homeCollectionViewCell.h"
#import "SearchViewController.h"

#import "RechargeController.h"
#import "OilRechargeController.h"
#import "ShopDetailsController.h"
#import "RecommendedController.h"
#import "LocationServeViewController.h"
#import "AddressManagerController.h"
#import "LocationServeManager.h"
#import "LocationServeManager.h"
#import "ReadWriteLocationCity.h"
#import "GoodListsModel.h"
#import "ShopDetailsController.h"

#import "DervativeAreaController.h"
#import "ActViewController.h"

#import "ProductSearchViewController.h"

#import "EasyToTescoNewsController.h"
#import "OrderSuccessViewController.h"
#import "RecordPhoneType.h"

#import "EasyNewsModel.h"
#import "EasyToTescoNewsDetailsVc.h"
#import "BusinessDetailsController.h"
#import "BusinessTableViewController.h"
#import "AdBussinessController.h"
#import "UITabBar+badge.h"

//间距
#define MAR_WIDTH 5

@interface HomeViewController ()<SDCycleScrollViewDelegate,CenterMenuViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UIAlertViewDelegate,CLLocationManagerDelegate,FirstHomeCellAd1Delegate>
{
    TopPullRefreshAnaimation *gifHeader;
    MBProgressHUD *progressHUD;
    NSDictionary *_urlDict;
    
    BOOL _JudgeFirstLocationCity;
    
    NSString *_cityString;
    
    NSDictionary *_oilCardDictionary;
    
    NSString *_pictStr;
    //分页
    NSUInteger refreshIndex;
}

@property(nonatomic,strong)SDCycleScrollView *cycleScrollView;
@property(nonatomic,strong)XRCarouselView *XrCarouselView;
@property(nonatomic,strong)CenterMenuView *menuView;

@property(nonatomic,strong)UICollectionView *homeCollectionView;

@property(nonatomic,strong)UILabel *sectionFirstLabel;
@property(nonatomic,strong)UILabel *sectionTwoLabel;

@property(nonatomic,strong)NSArray *menuTitleArr;

@property(nonatomic,strong)MBProgressHUD *HUD;

@property(nonatomic,strong)NSMutableArray *goodsListArray;

@property(nonatomic,strong)CLHomeHeader *header;
/**
 *  轮播数组
 */
@property(nonatomic,strong)NSArray *cycleUrlArray;
/**
 *  广告
 */
@property(nonatomic,strong)NSArray *cycleAd1Arr;
@property(nonatomic,strong)NSArray *cycleAd2Arr;
@property(nonatomic,strong)NSArray *cycleAd3Arr;
/**
 *  轮播数组
 */
@property(nonatomic,strong)NSMutableArray *actCycleArr;
/**
 *  可为快报
 */
@property(nonatomic,strong)NSMutableArray *EasyNewsArray;

@end

@implementation HomeViewController

static NSString * const firstReuseIdentifier =  @"firstReuseIdentifier";
static NSString * const secondReuseIdentifier=  @"secondReuseIdentifier";

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    NSString *locationCityString = [ReadWriteLocationCity ReadLocatinoCity];
    if (locationCityString.length) {
        self.navigationItem.leftBarButtonItem = [UIBarButtonItem LocationCityBarButtonItemWithImage:[UIImage imageNamed:@"selectCity"] highImage:nil target:self action:@selector(setLocationServeController) forControlEvents:UIControlEventTouchUpInside title:locationCityString];
    } else {
        self.navigationItem.leftBarButtonItem = [UIBarButtonItem LocationCityBarButtonItemWithImage:[UIImage imageNamed:@"selectCity"] highImage:nil target:self action:@selector(setLocationServeController) forControlEvents:UIControlEventTouchUpInside title:@"定位"];
        
    }
    
    [self loadUserInfoData];

}


- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithBackgroundImage:[UIImage imageNamed:@"shousuo"] highBackgroundImage:nil target:self action:@selector(searchDidClick) title:nil];
    
    [self addMainCollectionView];
    
    [LocationServeManager sharedLocationServeManager].delegate = self;
    
    _JudgeFirstLocationCity = YES;
    
    //版本更新监测
    [self judgeAppVersion];
    //判断当前网络状态
//    [self AFNetworkStatus];
    //首页轮播
    [self homeCycleViewPictureUrl];
    //ad
    [self homeActiveCAd1UrlData];
    [self homeActiveCAd2UrlData];
    [self homeActiveCAd3UrlData];
    
    [[RecordPhoneType sharedRecordPhoneType] RecordPheonType];
    
    refreshIndex = 1;
    //首页推荐商品上啦刷新
    [self addPullUpdateData];
    //首页推荐商品请求
    [self homeGetGoodsListsRequestData];
    
     [[[SDWebImageManager sharedManager] imageCache] clearDisk];
   
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(SetBadgeValue) name:@"badgeValue" object:nil];
    //[self showHudInView:self.view hint:[NSString stringWithFormat:@"%@",dict]];
    
    
}

- (void)SetBadgeValue {
    if ([ChatDemoHelper setUnReadMessageCount] > 0) {
        [self.tabBarController.tabBar showBadgeOnItemIndex:4];
    } else {
        [self.tabBarController.tabBar hideBadgeOnItemIndex:4];
    }
    
    
}


- (void)loadUserInfoData {
    if (!USERNAME) {
        return;
    }
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:@{@"username":USERNAME} AndMenthodName:@"api/User/info" completeBlock:^(id object) {
            _oilCardDictionary = object[@"data"];
        }] ;
    });
}

#pragma mark 手机版本检测
- (void)judgeAppVersion {
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSDictionary* infoDict = [[NSBundle mainBundle] infoDictionary];
        NSString* versionNum = [infoDict objectForKey:@"CFBundleShortVersionString"];
        NSLog(@"%@",versionNum);
        [[NetWorkSharedTools sharedNetWorkTools] GetObjectWithURLDict:@{} AndMenthodName:@"http://itunes.apple.com/lookup?id=1107627163" completeBlock:^(id object) {
            NSArray *array = object[@"results"];
            NSLog(@"%@",[array.firstObject objectForKey:@"version"]);
            
            if(array && array.firstObject && [array.firstObject objectForKey:@"version"])
            {
                NSString *note = [array.firstObject objectForKey:@"releaseNotes"];
                
                if ([[array.firstObject objectForKey:@"version"]  compare:versionNum options:NSNumericSearch] == NSOrderedDescending){
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"代金券全面来袭!赶快更新吧,第一时间体验新功能!" message:nil preferredStyle:UIAlertControllerStyleAlert];
                        
                        UIAlertAction *SettingAction = [UIAlertAction actionWithTitle:@"去更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                            
                            NSURL *url = [NSURL URLWithString:@"https://itunes.apple.com/cn/app/yi-le-gou-wu-ba/id1107627163?mt=8"];
                            [[UIApplication sharedApplication] openURL:url];
                            
                        }];
                        
                        [alert addAction:SettingAction];
                        
                        
//                        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"稍后"style:UIAlertActionStyleCancel handler:nil];
//                        [alert addAction:cancelAction];
                        
                        [self presentViewController:alert animated:YES completion:nil];
                    });
                }
            }
        }];
    });
}


#pragma mark 判断当前的网络状态
- (void)AFNetworkStatus
{

    NSLog(@"000000000-------------------%@",[self networkingStatesFromStatebar]);
}

- (NSString *)networkingStatesFromStatebar
{
    // 状态栏是由当前app控制的，首先获取当前app
    UIApplication *app = [UIApplication sharedApplication];
    
    NSArray *children = [[[app valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];
    
    int type = 0;
    for (id child in children) {
        if ([child isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]) {
            type = [[child valueForKeyPath:@"dataNetworkType"] intValue];
        }
    }
    NSString *stateString = @"wifi";
    
    switch (type) {
        case 0:
            stateString = @"notReachable";
            break;
            
        case 1:
            stateString = @"2G";
            break;
            
        case 2:
            stateString = @"3G";
            break;
            
        case 3:
            stateString = @"4G";
            break;
            
        case 4:
            stateString = @"LTE";
            break;
            
        case 5:
            stateString = @"wifi";
            break;
            
        default:
            break;
    }
    
    return stateString;
}

#pragma mark 手机定位
- (void)setLocationServeController {
    LocationServeViewController *locationVC = [[LocationServeViewController alloc] init];
    UINavigationController *locationServe = [[UINavigationController alloc] initWithRootViewController:locationVC];
    [self presentViewController:locationServe animated:YES completion:nil];
}

#pragma mark - CLLocationManangerDelegate
//定位成功以后调用
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    
    [[LocationServeManager sharedLocationServeManager] stop];
    CLLocation* location = locations.lastObject;
    [self reverseGeocoder:location];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"%s",__func__);
}

#pragma mark Geocoder
//反地理编码
- (void)reverseGeocoder:(CLLocation *)currentLocation {
    
    if (!_JudgeFirstLocationCity) {
        return;
    }
    
    CLGeocoder* geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        if(error || placemarks.count == 0){
            //            NSLog(@"error = %@",error);
        }else{
            CLPlacemark* placemark = placemarks.firstObject;
            
            NSString *appCityString = [NSString stringWithFormat:@"%@",[ReadWriteLocationCity ReadLocatinoCity]];
            
            NSLog(@"%@",[[placemark addressDictionary] objectForKey:@"City"]);
            
            NSString *string = [[placemark addressDictionary] objectForKey:@"City"];
            NSInteger length = string.length;
            _cityString = [string substringWithRange:NSMakeRange(0, length - 1)];
            
            [ReadWriteLocationCity saveLocationString:_cityString];
            
            NSLog(@"%@-------%@",appCityString,_cityString);
            if ([appCityString isEqualToString:_cityString]) {
                return;
            }
            
            NSString *TitleString = [NSString stringWithFormat:@"检测到您当前位置为:%@",[[placemark addressDictionary] objectForKey:@"City"]];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:TitleString message:@"是否切换城市" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alert.tag = 100101;
            [alert show];
        }
    }];
    _JudgeFirstLocationCity = NO;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 100101) {
        if (buttonIndex == 1) {
            NSLog(@"%@",_cityString);
            [ReadWriteLocationCity saveLocationCity:_cityString];
            self.navigationItem.leftBarButtonItem = [UIBarButtonItem LocationCityBarButtonItemWithImage:[UIImage imageNamed:@"selectCity"] highImage:nil target:self action:@selector(setLocationServeController) forControlEvents:UIControlEventTouchUpInside title:_cityString];
        }
    }
}


#pragma mark 搜索按钮点击方法
- (void)searchDidClick
{
    NSLog(@"searchDidClick");
    ProductSearchViewController *search = [[ProductSearchViewController alloc] init];
    search.goodsStutas = YES;
    [self.navigationController pushForm:self.navigationController pushToAndHidden:search];
}

- (void)addMainCollectionView
{
    UICollectionViewFlowLayout *flowlayout = [[UICollectionViewFlowLayout alloc] init];
    flowlayout.minimumLineSpacing = 2;
    flowlayout.minimumInteritemSpacing = 0;
    flowlayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    UICollectionView *homeCollectView = [[UICollectionView alloc] initWithFrame:CGRectMake(0,0,WIDTH, HEIGHT-112) collectionViewLayout:flowlayout];
    self.homeCollectionView = homeCollectView;
    _homeCollectionView.delegate = self;
    _homeCollectionView.dataSource = self;
    _homeCollectionView.backgroundColor = BACKGROUND_COLOR;
    [self.view addSubview:_homeCollectionView];
    
    //自适应大小
    //    _homeCollectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    
    
    //注册cell
    [self.homeCollectionView registerClass:[FirstHomeCell class] forCellWithReuseIdentifier:firstReuseIdentifier];
    [self.homeCollectionView registerClass:[homeCollectionViewCell class] forCellWithReuseIdentifier:secondReuseIdentifier];
    //    注册表头
    [self.homeCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"homeHeaderView"];
    //    [self.homeCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"sectionFirstView"];
    [self.homeCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"sectionTwoView"];
}

#pragma mark>>>>>>>>>>首页广告请求
- (void)homeCycleViewPictureUrl
{
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:@{@"position":@"App_Home_Carousel"} AndMenthodName:@"/api/Ads/lists" completeBlock:^(id object) {
//        NSLog(@"%@",object);
        if (JudgeBackDataCode) {
//            [_XrCarouselView clearDiskCache];
            self.cycleUrlArray = [object objectForKey:@"data"];
        }
        [self.homeCollectionView reloadData];
    }];
    
}
- (void)homeActiveCAd1UrlData
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 耗时的操作
        NSDictionary *params = @{@"position":@"App_Home_Ad1",};
        [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/Ads/lists" completeBlock:^(id object) {
            
//            NSLog(@"-----------%@",object);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if (JudgeBackDataCode) {
                    self.cycleAd1Arr = [object objectForKey:@"data"];
                    
                    [self.homeCollectionView reloadData];
                }
                
            });
            
        }];
        
    });
}

//ad2
- (void)homeActiveCAd2UrlData
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 耗时的操作
        NSDictionary *params = @{@"position":@"App_Home_Ad2",};
        [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/Ads/lists" completeBlock:^(id object) {
            
//            NSLog(@"-----------%@",object);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if (JudgeBackDataCode) {
                    self.cycleAd2Arr = [object objectForKey:@"data"];
                    [self.homeCollectionView reloadData];
                }
                
            });
            
        }];
        
    });
}

//ad3
- (void)homeActiveCAd3UrlData
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 耗时的操作
        NSDictionary *params = @{@"position":@"App_Home_Ad3",};
        [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/Ads/lists" completeBlock:^(id object) {
            
//            NSLog(@"-----------%@",object);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if (JudgeBackDataCode) {
                    self.cycleAd3Arr = [object objectForKey:@"data"];
                    [self.homeCollectionView reloadData];
                }
                
            });
            
        }];
        
    });
}



#pragma mark 可为快报
- (void)homeEasyToTescoNewsLoadData
{
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 耗时的操作
        NSDictionary *params = @{@"f_id":@"1",};
        [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/News/Fast" completeBlock:^(id object) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if (JudgeBackDataCode) {
                    
                    NSArray *arr = [object objectForKey:@"data"];
                    for (NSDictionary *tempDict in arr) {
                        EasyNewsModel *easyNewsModel = [[EasyNewsModel alloc] initWithDictionary:tempDict error:nil];
                        if (easyNewsModel) {
                            [self.EasyNewsArray addObject:easyNewsModel];
                        }
                        
                    }
                    
                    EasyNewsModel *firstModel = self.EasyNewsArray[0];
                    NSString *firstStr = firstModel.title;
                    
                    EasyNewsModel *secondModel = self.EasyNewsArray[1];
                    NSString *secondStr = secondModel.title;
                    
                    EasyNewsModel *thirdModel = self.EasyNewsArray[2];
                    NSString *thirdStr = thirdModel.title;
                    
                    EasyNewsModel *fourModel = self.EasyNewsArray[3];
                    NSString *fourStr = fourModel.title;
                    
                    _header.newses =  @[@[firstStr,secondStr],@[thirdStr,fourStr]];
                }
                
            });
            
        }];
        
        
    });
}

#pragma mark >>>>>>>>>获取商品列表
//上拉刷新
- (void)addPullUpdateData
{
    
    _homeCollectionView.mj_footer = [TopPullRefreshAnaimation footerWithRefreshingTarget:self refreshingAction:@selector(homeGetGoodsListsLoadMoreData)];
    
}

- (void)homeGetGoodsListsLoadMoreData
{
    refreshIndex ++;
    [self homeGetGoodsListsRequestData];
    [_homeCollectionView.mj_footer endRefreshing];
}

- (void)homeGetGoodsListsRequestData
{
    if (refreshIndex == 1) {
        [self.goodsListArray removeAllObjects];
    }
    NSString *P = [NSString stringWithFormat:@"%ld",refreshIndex];
    NSDictionary *params = @{@"p":[NSString stringWithFormat:@"%@",P],
                             @"recommend":@"5"
                             };
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 耗时的操作
        
        [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/goods/appGoodLists" completeBlock:^(id object) {
            
            //刷新
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if (JudgeBackDataCode) {
                    
                    NSDictionary *tempDict = object[@"data"];
                    NSArray *arr = [tempDict objectForKey:@"list"];
                    _urlDict = tempDict[@"picprex"];
                    
                    for (NSDictionary *dict in arr) {
                        GoodListsModel *goodListsModel = [[GoodListsModel alloc] initWithDictionary:dict error:nil];
                        if (goodListsModel) {
                            [self.goodsListArray addObject:goodListsModel];
                            
                        }
                    }
                    
                }else{
                    
                    [_homeCollectionView.mj_footer endRefreshingWithNoMoreData];
                }
                //菊花隐藏
                [progressHUD hide:YES];
                [progressHUD removeFromSuperViewOnHide];
                [_homeCollectionView reloadData];
                
            });
            
        }];
        
    });
}

#pragma mark>>>>>>>>DataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0 ) {
        return 1;
    }else {
        if (self.goodsListArray.count) {
            return self.goodsListArray.count;
        } else {
            return 0;
        }
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0 ) {
        
        FirstHomeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:firstReuseIdentifier forIndexPath:indexPath];
        cell.delegate = self;
        
        //立即
        cell.cycleArr = self.cycleAd1Arr;

        //ad2
        NSString *ad2ImgStr = [self.cycleAd2Arr[0] objectForKey:@"img"];
        [cell.ad2Img sd_setImageWithURL:[NSURL URLWithString:ad2ImgStr] placeholderImage:[UIImage imageNamed:@"homeCycleLoad.jpg"]];
        [cell.ad2btn addTarget:self action:@selector(homeFirstHomeCellAd2) forControlEvents:UIControlEventTouchUpInside];
        
        //累计+立即
        NSString *ad3ImgStr = [self.cycleAd3Arr[0] objectForKey:@"img"];
        [cell.ad3Img sd_setImageWithURL:[NSURL URLWithString:ad3ImgStr] placeholderImage:[UIImage imageNamed:@"homeCycleLoad.jpg"]];
        [cell.ad3btn addTarget:self action:@selector(homeFirstHomeCellAd3) forControlEvents:UIControlEventTouchUpInside];
        
        return cell;
        
    }else{
        
        homeCollectionViewCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:secondReuseIdentifier forIndexPath:indexPath];
        
        if (!self.goodsListArray.count) {
            return cell;
        }
        
        GoodListsModel *goodListsModel = self.goodsListArray[indexPath.item];
        
        NSString *string = [NSString stringWithFormat:@"%@%@",_urlDict[@"m"],goodListsModel.picurl];
        [cell.productImage sd_setImageWithURL:[NSURL URLWithString:string] placeholderImage:[UIImage imageNamed:@"goodsLoadJGG.jpg"]];
        cell.productImage.contentMode = UIViewContentModeScaleToFill;
        
        cell.productName.text = goodListsModel.title;
        cell.price.text = [NSString stringWithFormat:@"专享价: %@",goodListsModel.huiyuanjia];
        cell.backgroundColor = [UIColor whiteColor];
        return cell;
        
    }
    
}

#pragma mark>>>>>>>>>>>delegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section ==1) {
        
        //商品详情
        GoodListsModel *goodListsModel = self.goodsListArray[indexPath.item];
        ShopDetailsController *detailsVC = [[ShopDetailsController alloc] init];
        detailsVC.goodsId = goodListsModel.replaceID;
        [self.navigationController pushForm:self.navigationController pushToAndHidden:detailsVC];
        
    }    
}

//header组头大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        //头部视图size           轮播      menu         快报 标题
        return CGSizeMake(WIDTH,HEIGHT/5+HEIGHT/4+12+50*2 - 20 +5);
    }else{
        return CGSizeMake(WIDTH,50);
    }
}

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return CGSizeMake(WIDTH,HEIGHT/4);
    }else{
        return CGSizeMake(WIDTH/2-2, HEIGHT/2.8);
    }
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    if (section == 0) {
        
        return UIEdgeInsetsMake(1,0,0,0);
    }else{
        return UIEdgeInsetsMake(1,1,1,1);
    }
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    
    UICollectionReusableView *reusableView;
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) { //
        
        if (indexPath.section == 0) {
            //头部视图
            reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"homeHeaderView" forIndexPath:indexPath];
            [self addHeaderCycleView:reusableView];
            [self addCenterMenuView:reusableView];
            
        }else {
            reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"sectionTwoView" forIndexPath:indexPath];
            [reusableView addSubview:self.sectionTwoLabel];
        }
        
        return reusableView;
    }
    return  nil;
}

#pragma mark>>>>>>>>>>轮播
- (void)addHeaderCycleView:(UICollectionReusableView *)reusableView
{
    NSMutableArray *imageArr = [NSMutableArray array];
    for (NSDictionary *tempDict in self.cycleUrlArray) {
        NSString *str = tempDict[@"img"];
        [imageArr addObject:str];
    }
    
    [_cycleScrollView removeFromSuperview];
    if (_cycleScrollView == nil || imageArr.count > 0) {
        SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0,0,WIDTH,HEIGHT/5) delegate:nil placeholderImage:[UIImage imageNamed:@"homeCycleLoad.jpg"]];
        self.cycleScrollView = cycleScrollView;
        cycleScrollView.delegate = self;
        cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
        cycleScrollView.imageURLStringsGroup = imageArr;
        cycleScrollView.pageDotColor = [UIColor whiteColor];
        cycleScrollView.currentPageDotColor = DEFAULT_COLOR;
        [reusableView addSubview:cycleScrollView];
    }

}


#pragma mark>>>>>>>>菜单栏 //section 0 的组头
- (void)addCenterMenuView:(UICollectionReusableView *)reusableView
{
    if (self.menuView == nil) {
        self.menuView = [[CenterMenuView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_cycleScrollView.frame), WIDTH, HEIGHT/4+12) MenuArr:self.menuTitleArr];
        _menuView.backgroundColor = [UIColor whiteColor];
        [reusableView addSubview:_menuView];
        _menuView.delegate = self;
        
        _header = [[CLHomeHeader alloc] initWithFrame:CGRectMake(0,CGRectGetMaxY(_menuView.frame)+1,WIDTH,30)];
        
        [self homeEasyToTescoNewsLoadData];
        
        _header.newses = @[@[@"可为建材联盟,大有可为",@"可为建材联盟,大有可为"],@[@"可为建材联盟,大有可为",@"可为建材联盟,大有可为"]];
        
        __weak typeof(self) weakSelf = self;
        _header.cliclCelllable1 = ^{
            [weakSelf pushToEasyToTescoNewsControlller];
        };
        _header.cliclCelllable2 = ^{
            [weakSelf pushToEasyToTescoNewsControlller];
        };
        
        [reusableView addSubview:_header];
        
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,CGRectGetMaxY(_header.frame)+4, WIDTH,50)];
        [reusableView addSubview:label];
        label.text = @"   特惠活动";
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = [UIColor lightGrayColor];
        label.backgroundColor = [UIColor whiteColor];
    }
    
}

#pragma mark 可为快报
- (void)pushToEasyToTescoNewsControlller
{
    EasyToTescoNewsController *EasyToTescoNewsVc = [[EasyToTescoNewsController alloc] init];
    EasyToTescoNewsVc.title = @"可为建材快报";
    [self.navigationController pushForm:self.navigationController pushToAndHidden:EasyToTescoNewsVc];
}

#pragma mark >>>>>>>> 广告代理
/** 点击轮播图片回调 */
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    if (self.cycleUrlArray.count > 0) {
    NSLog(@"212121221%@",self.cycleUrlArray);
    NSInteger type = [[self.cycleUrlArray[index] objectForKey:@"type"] integerValue];
    NSString *valueStr = [self.cycleUrlArray[index] objectForKey:@"values"];
    NSString *title = [self.cycleUrlArray[index] objectForKey:@"title"];
    [self homeChooseType:type value:valueStr title:title];
    }
}

//ad1
- (void)homeFirstHomeCellAd1Index:(NSInteger)index
{
    
    if (self.cycleAd1Arr.count > 0) {
    NSInteger type = [[self.cycleAd1Arr[index] objectForKey:@"type"] integerValue];
    NSString *valueStr = [self.cycleAd1Arr[index] objectForKey:@"values"];
    NSString *title = [self.cycleAd1Arr[index] objectForKey:@"title"];
    
    [self homeChooseType:type value:valueStr title:title];
    }
}
//ad2
- (void)homeFirstHomeCellAd2
{
    
    if (self.cycleAd2Arr.count > 0) {
        NSInteger type = [[self.cycleAd2Arr[0] objectForKey:@"type"] integerValue];
        NSString *valueStr = [self.cycleAd2Arr[0] objectForKey:@"values"];
        NSString *title = [self.cycleAd2Arr[0] objectForKey:@"title"];
        
        [self homeChooseType:type value:valueStr title:title];
    }
    
}
//ad3
- (void)homeFirstHomeCellAd3
{
    if (self.cycleAd3Arr.count > 0) {
        NSInteger type = [[self.cycleAd3Arr[0] objectForKey:@"type"] integerValue];
        NSString *valueStr = [self.cycleAd3Arr[0] objectForKey:@"values"];
        NSString *title = [self.cycleAd3Arr[0] objectForKey:@"title"];
        
        [self homeChooseType:type value:valueStr title:title];
    }
}


//广告choose
- (void)homeChooseType:(NSInteger)type value:(NSString *)value title:(NSString *)title
{
    switch (type) {
        case 1:
            //商品
        {
            ShopDetailsController *detailsVC = [[ShopDetailsController alloc] init];
            detailsVC.goodsId = value;
            detailsVC.title = title;
            [self.navigationController pushForm:self.navigationController pushToAndHidden:detailsVC];
            break;
            
        }
            
        case 2:
            //商品列表
        {
            RecommendedController*recommendedVC = [[RecommendedController alloc] init];
            recommendedVC.product_id = value;
            recommendedVC.title = title;
            recommendedVC.is_actPush = YES;
            [self.navigationController pushForm:self.navigationController pushToAndHidden:recommendedVC];
            
            break;
        }
            
        case 3:
            //文章
        {
            EasyToTescoNewsDetailsVc *newsDetailsVC = [[EasyToTescoNewsDetailsVc alloc] init];
            newsDetailsVC.link = value;
            newsDetailsVC.title = title;
            [self.navigationController pushForm:self.navigationController pushToAndHidden:newsDetailsVC];
            break;
        }
        
        case 4:
            //店铺
        {
            BusinessDetailsController *detailVC = [[BusinessDetailsController alloc] init];
            detailVC.bussinessId = value;
            [self.navigationController pushForm:self.navigationController pushToAndHidden:detailVC];
            break;
        }
            
        case 5:
            //店铺列表
        {
            AdBussinessController *AdBussinessVC = [[AdBussinessController alloc] init];
            AdBussinessVC.value = value;
            AdBussinessVC.title = title;
            [self.navigationController pushForm:self.navigationController pushToAndHidden:AdBussinessVC];
            break;
        }
        default:
            break;
    }
}

//View代理方法
#pragma mark >>>>>>>>>>> menu代理方法
- (void)homeMenuDidSelectedAtIndex:(NSInteger)index
{
    if (index == 10) {
        RechargeController *rechargeVC = [[RechargeController alloc] init];
        rechargeVC.title = @"话费充值";
        [self.navigationController pushForm:self.navigationController pushToAndHidden:rechargeVC];
    }else if (index == 11) {
        
        OilRechargeController*oilVC = [[OilRechargeController alloc] init];
        oilVC.title = @"油卡充值";
        oilVC.oilNumberString = _oilCardDictionary[@"youka"];
        [self.navigationController pushForm:self.navigationController pushToAndHidden:oilVC];
        
    }else if (index == 12){
        
        DervativeAreaController *DervativeAreaVC = [[DervativeAreaController alloc] init];
        DervativeAreaVC.title = @"微商专区";
        DervativeAreaVC.value = @"";
        [self.navigationController pushForm:self.navigationController pushToAndHidden:DervativeAreaVC];
        
    }else if(index == 13){
        
        RecommendedController*recommendedVC = [[RecommendedController alloc] init];
        recommendedVC.title = @"精品推荐";
        [self.navigationController pushForm:self.navigationController pushToAndHidden:recommendedVC];
        
    }else if (index == 14){
        
        RecommendedController*recommendedVC = [[RecommendedController alloc] init];
        recommendedVC.title = @"农特产品";
        recommendedVC.is_Agricultural = YES;
        [self.navigationController pushForm:self.navigationController pushToAndHidden:recommendedVC];
        
    } else  if(index == 15){
        //积分特惠
        RecommendedController*recommendedVC = [[RecommendedController alloc] init];
        recommendedVC.title = @"可为特惠";
        recommendedVC.is_teHui = YES;
        [self.navigationController pushForm:self.navigationController pushToAndHidden:recommendedVC];
        
    }else  if(index == 16){
        
         //活动
        ActViewController *ActViewVc = [[ActViewController alloc] init];
        ActViewVc.title = @"活动专区";
        ActViewVc.homePush = YES;
        [self.navigationController pushForm:self.navigationController pushToAndHidden:ActViewVc];
        
    }else{
        //竞拍
//        弹框
//        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"功能正在持续建设中.." preferredStyle:UIAlertControllerStyleAlert];
//
//        UIAlertAction *okay = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//
//        }];
//
//        [alert addAction:okay];
//        [self presentViewController:alert animated:YES completion:nil];
        
//        ChatViewController *chat = [[ChatViewController alloc] initWithConversationChatter:@"15200000001" conversationType:EMConversationTypeChat];
//        chat.FromSellerNumber = @"15200000001";
//        chat.title = @"15695880000";
//        [self.navigationController pushForm:self.navigationController pushToAndHidden:chat];
        
        RecommendedController*recommendedVC = [[RecommendedController alloc] init];
        recommendedVC.title = @"旅游";
        recommendedVC.is_tour = YES;
        [self.navigationController pushForm:self.navigationController pushToAndHidden:recommendedVC];
        
    }
    
}



#pragma mark>>>>>>>>>>>>> 懒加载
- (NSArray *)menuTitleArr
{
    if (!_menuTitleArr) {
        _menuTitleArr = @[@"话费充值",@"石油充值",@"微商专区",@"精品推荐",@"农特产品",@"可为特惠",@"活动专区",@"旅游"];
    }
    return _menuTitleArr;
}

- (UILabel *)sectionFirstLabel
{
    if (!_sectionFirstLabel) {
        _sectionFirstLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,MAR_WIDTH, WIDTH, HEIGHT/15-MAR_WIDTH)];
        _sectionFirstLabel.text = @"   竞拍";
        _sectionFirstLabel.font = [UIFont systemFontOfSize:14];
        _sectionFirstLabel.textColor = [UIColor lightGrayColor];
        _sectionFirstLabel.backgroundColor = [UIColor whiteColor];
    }
    return _sectionFirstLabel;
}
//HEIGHT/15-MAR_WIDTH/2
- (UILabel *)sectionTwoLabel
{
    if (!_sectionTwoLabel) {
        _sectionTwoLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,3, WIDTH,50-3)];
        _sectionTwoLabel.text = @"   精品推荐";
        _sectionTwoLabel.font = [UIFont systemFontOfSize:14];
        _sectionTwoLabel.textColor = [UIColor lightGrayColor];
        _sectionTwoLabel.backgroundColor = [UIColor whiteColor];
    }
    return _sectionTwoLabel;
}

- (NSMutableArray *)goodsListArray {
    if (!_goodsListArray) {
        _goodsListArray = [NSMutableArray array];
    }
    return _goodsListArray;
}

- (NSArray *)cycleUrlArray
{
    if (!_cycleUrlArray) {
        _cycleUrlArray = [[NSArray alloc] init];
    }
    return _cycleUrlArray;
}

- (NSMutableArray *)EasyNewsArray
{
    if (!_EasyNewsArray) {
        _EasyNewsArray = [NSMutableArray array];
    }
    return _EasyNewsArray;
}


@end
